package io.gitee.xyuesheng.day05;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestSort {
    @Test
    public void test() {
        List<Student> students = new ArrayList<>();
        students.add(new Student("zhangsan", 18, "1001"));
        students.add(new Student("lisi", 25, "1002"));
        students.add(new Student("wangwu", 19, "1003"));
        students.add(new Student("zhaoliu", 15, "1004"));

        for (Student s : students) {
            System.out.println(s);
        }

        System.out.println("########");
        //集合排序需要制定一个比较器
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //比较名字
                //o1.getName().compareTo(o2.getName());
                return o1.getAge() - o2.getAge();
            }
        });
        for (Student s : students) {
            System.out.println(s);
        }
    }


    @Test
    public void testComparable() {
        List<Student> students = new ArrayList<>();
        students.add(new Student("zhangsan", 18, "1001"));
        students.add(new Student("lisi", 35, "1002"));
        students.add(new Student("wangwu", 29, "1003"));
        students.add(new Student("zhaoliu", 25, "1004"));

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {

                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Student s : students) {
            System.out.println(s);
        }
    }

    //如果list集合里面的元素，实现了comparable（定义比较规则）接口
    //Collections.sort就会按照元素定义的比较规则进行排序
    @Test
    public void testString() {
        List<String> list = new ArrayList<>();
        list.add("zhangsan");
        list.add("lisi");
        list.add("wangwu");
        list.add("zhaoliu");

        Collections.sort(list);

        for (String s : list) {
            System.out.println(s);
        }
    }

}
